#!/usr/bin/python
#coding=utf-8

import xlwt, sys, os
from PyQt4 import Qt, QtCore, QtGui

def csv2Excel(file_names, res_name, work_dir):
	res_file = open(os.path.join(work_dir, res_name), "w")

	fileList = [str(f) for f in file_names]
	csvFileList = [f for f in fileList if f.split('.')[1] in ("csv")]
	rownum = 0
	for f in csvFileList:
		name = os.path.split(f)[1].upper()
		if name.startswith('ORDERS'):
			type_tr = "Orders"
		elif name.startswith('RCORDERS'):
			type_tr = "RCOrders"
		elif name.startswith('NEGDEALS'):
			type_tr = "Negdeals"
		elif name.startswith('RNEGDEALS'):
			type_tr = "RNegdeals"
		elif name.startswith('RCNEGDEALS'):
			type_tr = "RCNegdeals"
		elif name.startswith('PRIMARY'):
			type_tr = "Primary"
		elif name.startswith('TRANSFERS'):
			type_tr = "Transfers"
		else:
			type_tr = "Unknown"
			print("Error name file %s" % name)								
		res_file.write(type_tr)				

		with open(f, 'r') as f:
			for row in f.readlines():
				kol = row.count(';') + 1
				res_file.write(';'+row)		
			res_file.write(';' * kol + os.linesep)		

app = Qt.QApplication(sys.argv)
window = Qt.QWidget()
le = QtGui.QLineEdit(window)

def choose_file():
	file_names = QtGui.QFileDialog.getOpenFileNames(window, "Open Data File", ".", "CSV data files (*.csv)")
	if file_names:
		work_dir = os.path.split(str(file_names[0]))[0]
		csv2Excel(file_names, str(le.text()), work_dir)

if __name__ == "__main__" :
	layout2 = Qt.QVBoxLayout()
	layout2.setContentsMargins(3, 3, 3, 3)
	layout2.setSpacing(3)

	le.setText("res.csv")
	button1 = Qt.QPushButton(u"Выберите файлы")
	QtCore.QObject.connect(button1, QtCore.SIGNAL("clicked()"), choose_file)
	
	layout2.addWidget(le)
	layout2.addWidget(button1)

	window.setLayout(layout2)
	window.show()
	app.exec_()
